package com.example.moneygrosService;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class BluetoothService extends Service {
	private static final String TAG = BluetoothService.class.getSimpleName();

	public static final int REQUEST_ENABLE_BT = 2;
//	public static final UUID MONEYGROS_BT_SERVICE_UUID = UUID.fromString("MONEYGROS_BT_SERVICE");
	public static final UUID MONEYGROS_BT_SERVICE_UUID = UUID.fromString("3817600e-5ff4-45dc-924f-c8cb9f650320");
	
	public static final String MONEYGROS_BT_SERVICE_NAME = "MoneyGros-BT-Service";

	
    // Reading data from Bluetooth HDP device.
    public static final int STATUS_READ_DATA = 104;
    // Done with reading data.
    public static final int STATUS_READ_DATA_DONE = 105;
    
	static private boolean isRunning;
	private BluetoothAdapter mBluetoothAdapter;
	
	private Looper mServiceLooper;
	private Context mContext;

    private Messenger mClient;
    
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    
	public BluetoothService() {
		// TODO Auto-generated constructor stub
		isRunning=false;
		mContext=this;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		setBluetooth();
        return mMessenger.getBinder();
	}
	
	@Override
	public void onCreate() {
		Toast.makeText(this, "BluetoothService Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
	       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
	            // Bluetooth adapter isn't available.  The client of the service is supposed to
	            // verify that it is available and activate before invoking this service.
	            stopSelf();
	            return;
	        }
//	        if (!mBluetoothAdapter.getProfileProxy(this, mBluetoothServiceListener,
//	                BluetoothProfile.HEALTH)) {
//	            Toast.makeText(this, R.string.bluetooth_health_profile_not_available,
//	                    Toast.LENGTH_LONG);
//	            stopSelf();
//	            return;
//	        }
		// Start up the thread running the service.  Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.  We also make it
		// background priority so CPU-intensive work will not disrupt our UI.
//		HandlerThread thread = new HandlerThread("ServiceStartArguments",
//				Process.THREAD_PRIORITY_BACKGROUND);
//		thread.start();
 
//		setBluetooth();

		// Get the HandlerThread's Looper and use it for our Handler 
//		mServiceLooper = thread.getLooper();
//		new BluetoothHandler(mServiceLooper);
		
//	    ServeurBluetooth server = new ServeurBluetooth();
//		server.start();
		
//        showNotification();
	}
	
	private void setBluetooth() {
		// TODO Auto-generated method stub
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
		    // Device does not support Bluetooth
			stopSelf();
		} else {

			if (!mBluetoothAdapter.isEnabled()) {
//				
//				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//				this.startActivity(enableBtIntent, REQUEST_ENABLE_BT);
				stopSelf();
			} else {
				
			}
		}

	}
	

    
	// Sends an update message to registered UI client.
	    private void sendMessage(int what, int value) {
	        if (mClient == null) {
	            Log.d(TAG, "No clients registered.");
	            return;
	        }

	        try {
	            mClient.send(Message.obtain(null, what, value, 0));
	        } catch (RemoteException e) {
	            // Unable to reach client.
	            e.printStackTrace();
	        }
	    }
	    
	    // Thread to read incoming data received from the HDP device.  This sample application merely
	    // reads the raw byte from the incoming file descriptor.  The data should be interpreted using
	    // a health manager which implements the IEEE 11073-xxxxx specifications.
	    private class ReadThread extends Thread {
	        private ParcelFileDescriptor mFd;

	        public ReadThread(ParcelFileDescriptor fd) {
	            super();
	            mFd = fd;
	        }

	        @Override
	        public void run() {
	            FileInputStream fis = new FileInputStream(mFd.getFileDescriptor());
	            final byte data[] = new byte[8192];
	            try {
	                while(fis.read(data) > -1) {
	                    // At this point, the application can pass the raw data to a parser that
	                    // has implemented the IEEE 11073-xxxxx specifications.  Instead, this sample
	                    // simply indicates that some data has been received.
	                    sendMessage(STATUS_READ_DATA, 0);
	                }
	            } catch(IOException ioe) {}
	            if (mFd != null) {
	                try {
	                    mFd.close();
	                } catch (IOException e) { /* Do nothing. */ }
	            }
	            sendMessage(STATUS_READ_DATA_DONE, 0);
	        }
	    }
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		if (requestCode == REQUEST_ENABLE_BT) {
//			if(resultCode == RESULT_OK){
//				setBluetooth();
//			}
//
//			if (resultCode == RESULT_CANCELED) {
//				this.stopSelf();
//			}
//		}
//	}

	    // Callbacks to handle connection set up and disconnection clean up.
	    private final BluetoothProfile.ServiceListener mBluetoothServiceListener =
	            new BluetoothProfile.ServiceListener() {
	        public void onServiceConnected(int profile, BluetoothProfile proxy) {
	            if (profile == BluetoothProfile.HEALTH) {
	            	// TODO: c'est sale
//	                mBluetoothHealth = (BluetoothHealth) proxy;
	                if (Log.isLoggable(TAG, Log.DEBUG))
	                    Log.d(TAG, "onServiceConnected to profile: " + profile);
	            }
	        }

	        public void onServiceDisconnected(int profile) {
	            if (profile == BluetoothProfile.HEALTH) {
//	                mBluetoothHealth = null;
	            	// TODO: c'est sale
	            }
	        }
	    };

	    // Handles events sent by {@link HealthHDPActivity}.
	    private class IncomingHandler extends Handler {
	        @Override
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	                // Register UI client to this service so the client can receive messages.
//	                case MSG_REG_CLIENT:
//	                    Log.d(TAG, "Activity client registered");
//	                    mClient = msg.replyTo;
//	                    break;
//	                // Unregister UI client from this service.
//	                case MSG_UNREG_CLIENT:
//	                    mClient = null;
//	                    break;
//	                // Register health application.
//	                case MSG_REG_HEALTH_APP:
//	                    registerApp(msg.arg1);
//	                    break;
//	                // Unregister health application.
//	                case MSG_UNREG_HEALTH_APP:
//	                    unregisterApp();
//	                    break;
//	                // Connect channel.
//	                case MSG_CONNECT_CHANNEL:
//	                    mDevice = (BluetoothDevice) msg.obj;
//	                    connectChannel();
//	                    break;
//	                // Disconnect channel.
//	                case MSG_DISCONNECT_CHANNEL:
//	                    mDevice = (BluetoothDevice) msg.obj;
//	                    disconnectChannel();
//	                    break;
	                default:
	                    super.handleMessage(msg);
	            }
	        }
	    }
}
